package dse.messages.multiversion;

import java.util.*;

import dse.*;
import dse.messages.*;
import dse.messages.singleversion.ShareDownloader;

public class GetORPTransaction extends Transaction implements
		ShareDownloader, VersionReader {

	//private Node requester;
	private DataObject desiredObject;
	private LinkedList<Node> residentNodes;
	private boolean failed;
	private TreeMap<Version, LinkedList<Node>> sharesDownloaded;
	
	//private TreeMap<Version, LinkedList<Node>> versionsDownloaded;
	private int requestShareCount;
	private int validShareCount;
	private int maxFailure;
	private int successCount;
	private int failureCount;
	private int maxTS;
	//private Version maxStableVersion;
	private Version maxVersion;
	private int sharesToBeUpdate;
	private boolean hasRequestMoreShares;
	private boolean hasRequestPreviousShares;
	private int round;
	private double begin;
	private double end;
	
	public GetORPTransaction(Experiment experiment,
			int id,
			Node requester,
			DataObject desiredObject,
			double time
			)
	{
		super(id, requester, experiment, time);
		
		//this.requester = requester;
		this.desiredObject = desiredObject;
		this.failed = false;
		this.requestShareCount = 0;
		this.validShareCount = 0;
		this.maxFailure = experiment.modules().nodeEventScheduler().getEventsPerPeriod();
		this.successCount = 0;
		this.failureCount = 0;
		this.maxTS = 0;
		this.maxVersion = null;
		//this.maxStableVersion = null;
		this.sharesToBeUpdate = desiredObject.shareCount();
		if(isUpdate && isPartialUpdate)
		{
			this.sharesToBeUpdate = (int)(desiredObject.shareCount()*experiment.configuration().getRandom().nextDouble());
			//System.err.println("Partial Update:" + sharesToBeUpdate);
		}
		this.hasRequestMoreShares = false;
		this.hasRequestPreviousShares = false;
		this.round = 1;
	}

	@Override
	public void start(ExperimentRecorder recorder) {
		// TODO Auto-generated method stub
		residentNodes = MessageUtil.getNodesByDht(experiment.network(), requester, desiredObject, experiment.modules().assigner());		

		if(isUpdate)
		{
			recorder.dataUpdateInitiated(super.id, requester, desiredObject, startTime);
			recorder.debug(this, "start", startTime);
			//int srf = experiment.modules().shareRequestDecisionMaker().sharesToRequestFor(desiredObject)
				//		+ this.maxFailure*2;
			this.requestShareCount = desiredObject.shareCount();
			this.validShareCount = requestShareCount - this.maxFailure;
			
			for (int i=0; (i<requestShareCount) && (i<residentNodes.size()); i++)
				sendMaxTSRequest(recorder, residentNodes.get(i), startTime);
			//for (int i=0; (i<srf) && (i<residentNodes.size()); i++)
				//System.out.println(this.id + " : " + experiment.modules().costCalculator().distance(experiment.network(), requester, residentNodes.get(i)));
		}
		else
		{
			recorder.dataRequestInitiated(super.id, requester, desiredObject, startTime);
			recorder.debug(this, "start", startTime);
			
			this.requestShareCount = experiment.modules().shareRequestDecisionMaker().sharesToRequestFor(desiredObject);
			this.requestShareCount = this.requestShareCount>this.desiredObject.shareCount()?this.desiredObject.shareCount():this.requestShareCount;
			//System.out.println(this.requestShareCount);
			this.validShareCount = desiredObject.requiredShareCount();
			for(int i=0; (i<requestShareCount)&&(i<residentNodes.size()); i++)
			{
				sendGetLatestShareRequest(recorder, residentNodes.get(i), startTime, i);
			}
		}
	}
	
	@Override
	public void shareDownloaded (ExperimentRecorder recorder, Node from,
			DataObject dobj, int shareIndex, double timeLeft)
	{
	}
	
	@Override
	public void shareDownloadFailed (ExperimentRecorder recorder, DataObject dobj, 
			int shareIndex, double timeLeft)
	{		
	}
	
	@Override
	public boolean isDoneDownloadingShares ()
	{
		return (failed || finished);
	}
	
	private void sendGetLatestShareRequest(ExperimentRecorder recorder, Node node, double time, int i)
	{
		if (node == null) {
			// We should turn this into a warning ...
			recorder.warn(
					"Share assigner failed to map share to node in cluster!"
					);
			return;
		}
		
		Message m = super.createRequestLatestShareMessage(requester, node, desiredObject, 
				MessagePurpose.DataObjectRequest, this);
		recorder.debug(this, "new msg: " + m, time);
		experiment.messageQueue().enqueueMessage(m, time);
		if(i == 0)
			begin = m.endTime();
		else if(i == (requestShareCount-1) || i==(this.residentNodes.size()-1)){
			end = m.endTime();
			recorder.readDuration(end - begin);
		}
	}
	
	private void sendGetPreviousShareRequest(ExperimentRecorder recorder, Version version, 
			Node node, double time)
	{
		if (node == null) {
			// We should turn this into a warning ...
			recorder.warn(
					"Share assigner failed to map share to node in cluster!"
					);
			return;
		}
		
		Message m = super.createRequestPreviousShareMessage(requester, node, desiredObject, 
				maxVersion, MessagePurpose.DataObjectRequest, this, round);
		recorder.debug(this, "new msg: " + m, time);
		experiment.messageQueue().enqueueMessage(m, time);
	}
	
	@Override
	public void shareUpdated (ExperimentRecorder recorder, Node to,
			DataObject dobj, int shareIndex, double timeLeft)
	{
		if(isUpdate) {		
			//this.processedUpdateMessage++;
			//this.processedSuccessUpdateMessage++;
			this.successCount++;
			if((successCount+failureCount) >= this.sharesToBeUpdate)
			{
				if(this.successCount >= validShareCount)
					transactionSucceed(recorder, timeLeft);
				else
					transactionFailed(recorder, timeLeft);
			}
		}
	}
	
	@Override
	public void shareUpdateFailed (ExperimentRecorder recorder, DataObject dobj, 
			int shareIndex, double timeLeft)
	{
		if(isUpdate) {
			this.failureCount++;
			if((successCount + failureCount) >= this.sharesToBeUpdate)
			{
				if(this.successCount >= validShareCount)
					transactionSucceed(recorder, timeLeft);
				else
					transactionFailed(recorder, timeLeft);
			}
		}
	}
	
	@Override
	public boolean isDoneUpdatingShares ()
	{
		return (failed || finished);
	}
	
	private void sendUpdateShareRequest(ExperimentRecorder recorder, Node node, Version version, Double time)
	{
		if (node == null) {
			// We should turn this into a warning ...
			recorder.warn(
					"Share assigner failed to map share to node in cluster!"
					);
			return;
		}
		
		Message m = super.createShareUpdateV3Message(requester, node, desiredObject, 
				version, MessagePurpose.DataObjectUpdate, this);
		recorder.debug(this, "new msg: " + m, time);
		experiment.messageQueue().enqueueMessage(m, time);
		/*if(i == 0)
			begin = m.endTime();
		else if(i == this.sharesToBeUpdate-1){
			end = m.endTime();
			recorder.updateDuration(end - begin);
		}*/
	}
	
	@Override
	public void readVersion(ExperimentRecorder recorder, TreeSet<Version> versions, double timeLeft, Node from){}
	
	public void readVersion(ExperimentRecorder recorder, Node from, Version version, double timeLeft)
	{
		if(failed)
			return;
		if(version == null)
		{
			failureCount++;
			//this.residentNodes.remove(from);
			if(!this.hasRequestPreviousShares)
			{
				if(failureCount > desiredObject.shareCount()-validShareCount)
				{
					System.out.println("Failed number exceeds the maximum number");
					transactionFailed(recorder, timeLeft);
				}
				else if(failureCount>(requestShareCount-validShareCount) && residentNodes.size() > this.requestShareCount)
				{
					this.requestShareCount++;
					this.sendGetLatestShareRequest(recorder, this.residentNodes.get(this.requestShareCount-1), timeLeft, -1);
					System.err.println("request from more shares");
					if(this.startTime >= 5){
						if(this.hasRequestMoreShares)
							recorder.requestMoreShares(desiredObject, false);
						else{
							this.hasRequestMoreShares = true;
							recorder.requestMoreShares(desiredObject, true);
						}
					}
				}
				return;
			}
			else if(failureCount >= requestShareCount)
			{
				System.out.println(this.id + "Failed number exceeds the maximum number for read previous");
				transactionFailed(recorder, timeLeft);
				return;
			}
			if(successCount+failureCount>= requestShareCount)
				processVersion(recorder, timeLeft);
			return;
		}
		if(sharesDownloaded == null)
			sharesDownloaded = new TreeMap<Version, LinkedList<Node>>();
		//if(successCount >= validShareCount)
			//return;
		successCount++;
		if(this.sharesDownloaded.get(version) == null)
		{
			this.sharesDownloaded.put(version, new LinkedList<Node>());
			this.sharesDownloaded.get(version).add(from);
		}
		else
			this.sharesDownloaded.get(version).add(from);
		
		if(successCount + failureCount >= requestShareCount)
			processVersion(recorder, timeLeft);
	}
	
	public void readVersion(ExperimentRecorder recorder, int seq, double time){
		if(seq == -1)
		{
			failureCount++;
			return;
		}
		successCount++;
		if(this.maxTS < seq)
			this.maxTS = seq;
		if(successCount+failureCount >= requestShareCount){
			successCount = 0;
			failureCount = 0;
			if(this.maxTS >= requester.getSequence())
				requester.setSequence(this.maxTS);
			Version version = new Version(requester.sequence(), requester.id());
			for(int i=0; (i<this.sharesToBeUpdate) && (i<residentNodes.size()); i++)
				sendUpdateShareRequest(recorder, residentNodes.get(i), version, time);
		}
	}
	public void readVersion(ExperimentRecorder recorder, int seq, int index, double time){}
	public void readVersion(ExperimentRecorder recorder, double time, LinkedList<Version> versions, Version version, Node from){}
	
	private void sendMaxTSRequest(ExperimentRecorder recorder, Node node, Double time)
	{
		if (node == null) {
			// We should turn this into a warning ...
			recorder.warn(
					"Share assigner failed to map share to node in cluster!"
					);
			return;
		}
		
		Message m = super.createRequestMaxTSMessage(
				requester, 
				node,
				desiredObject, 
				MessagePurpose.DataObjectUpdate,
				this
				);
		recorder.debug(this, "new msg: " + m, time);
		experiment.messageQueue().enqueueMessage(m, time);
	}
	
	/*private void processVersions(ExperimentRecorder recorder, double timeLeft)
	{
		if((versionsDownloaded==null) || (versionsDownloaded.size()==0))
		{
			transactionFailed(recorder, timeLeft);
			return;
		}
		if(this.versionsDownloaded.lastKey().getSequence()>requester.getSequence())
			requester.setSequence(versionsDownloaded.lastKey().getSequence());
		
		Map.Entry<Version, LinkedList<Node>> version = versionsDownloaded.pollLastEntry();
		while((versionsDownloaded.size()>0) && (version.getValue().size() < desiredObject.shareCount()))
		{
			version = versionsDownloaded.pollLastEntry();
		}
		maxStableVersion = version.getKey();
		
		this.successCount = 0;
		this.failureCount = 0;
		/*if(this.isUpdate){
			for(int i=0; i<this.sharesToBeUpdate; i++)
				sendUpdateShareRequest(recorder, residentNodes.get(i), timeLeft, i);
		}*/
		//else{
		/*for(Node n : version.getValue())
			SendRequestDesignatedShareRequest(recorder, maxStableVersion, n, timeLeft);
		//transactionSucceed(recorder, timeLeft);
	}*/
	
	private void processVersion(ExperimentRecorder recorder, double timeLeft)
	{
		if((sharesDownloaded==null) || (sharesDownloaded.size()==0))
		{
			transactionFailed(recorder, timeLeft);
			return;
		}
		
		maxVersion = sharesDownloaded.lastKey();
		if(maxVersion.getSequence()>requester.getSequence())
			requester.setSequence(maxVersion.getSequence());
		Map.Entry<Version, LinkedList<Node>> vn = sharesDownloaded.pollLastEntry();
		while((vn.getValue().size()<validShareCount) && (sharesDownloaded.size()>0))
		{
			vn = sharesDownloaded.pollLastEntry();
		}
		
		if(vn.getValue().size() >= validShareCount)
		{
			transactionSucceed(recorder, timeLeft);
		}		
		else if(sharesDownloaded.size() == 0)
		{	
			//int srf = experiment.modules().shareRequestDecisionMaker().sharesToRequestFor(desiredObject)
				//+ this.maxFailure*2;
			if(this.startTime >= 5){
				if(this.hasRequestPreviousShares){
					recorder.requestPreviousShares(desiredObject, false);
				}	
				else{
					this.hasRequestPreviousShares = true;
					recorder.requestPreviousShares(desiredObject, true);
				}
			}
			failureCount = 0;
			successCount = 0;
			this.round++;
			this.sharesDownloaded.clear();
			//for(int i=0; (i<srf)&&(i<residentNodes.size()); i++)
			//if(this.id == 178)
				//System.out.println("get previous than " + maxVersion.toString());
			for(int i=0; (i<requestShareCount)&&(i<residentNodes.size()); i++)	
				sendGetPreviousShareRequest(recorder, maxVersion, residentNodes.get(i), timeLeft);
		}
		else
			transactionFailed(recorder, timeLeft);
	}
	
	private void transactionSucceed(ExperimentRecorder recorder, double timeLeft)
	{
		finished = true;
		failed  = false;
		//System.out.println("Data ID : " + desiredObject.id() + "Version : " + maxVersion.getSequence() + " , " + maxVersion.getClientID());
		if(isUpdate)
		{
			recorder.debug(
					"GetDhtDataSharesWithVersionTransaction trans#" + super.id + 
					" is finshed!!!"
					);
			recorder.dataUpdateFinished(super.id, requester, desiredObject, true, timeLeft);
		}
		else
		{
			recorder.debug(
					"GetDhtDataSharesWithVersionTransaction trans#" + super.id + 
					" is finshed!!!"
					);
			recorder.dataRequestFinished(super.id, requester, desiredObject, true, this.residentNodes.get(this.validShareCount-1),
					false, timeLeft);
		}
	}
	
	private void transactionFailed (ExperimentRecorder recorder, double timeLeft)
	{
		recorder.debug(this, "transFailed", timeLeft);
		
		finished = true;
		failed = true;
		if(isUpdate)
			recorder.dataUpdateFinished(super.id, requester, desiredObject, false, timeLeft);
		else
			recorder.dataRequestFinished(super.id, requester, desiredObject, false, null, false, timeLeft);
	}
	public Transaction getTransaction(){
		return this;
	}
}